package com.epimarket.model;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public final class EMF
{
	private static final EntityManagerFactory emfInstance = 
			Persistence.createEntityManagerFactory("epimarket");
	
	private EMF(){}
	
	public static EntityManagerFactory get()
	{
		return emfInstance;
	}
	
	public static void persist(Object obj)
	{
		EntityManager em = EMF.get().createEntityManager();
		em.getTransaction().begin();
		em.persist(obj);
		em.getTransaction().commit();
		em.close();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object find(Class cl, Long id)
	{
		return EMF.get().createEntityManager().find(cl, id);
	}
	
	public void delete(Object obj)
	{

		EntityManager em = EMF.get().createEntityManager();
		em.getTransaction().begin();
		em.remove(obj);
		em.getTransaction().commit();
		em.close();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static List<Object> findAll(Class cl)
	{
		return EMF.get().createEntityManager()
				.createQuery("SELECT a FROM " + cl.getName() + " a")
				.getResultList();
	}
	
	public static void update(Object obj)
	{
		EntityManager em = EMF.get().createEntityManager();
		em.getTransaction().begin();
		em.merge(obj);
		em.getTransaction().commit();
		em.close();
	}
	
	@SuppressWarnings("rawtypes")
	public static Long count(Class cl)
	{
		return (Long) EMF.get().createEntityManager()
			.createQuery("SELECT COUNT(a) FROM " + cl.getName() + " a")
			.getSingleResult();
	}

}
